﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Crochet.Core.Policy
{
	public class RetryOnExceptionExecutionPolicy : BaseExecutionPolicy
	{
		protected bool	bForceThrow;
		protected int	iRetries, iDelay;

		public RetryOnExceptionExecutionPolicy(int iRetries, int iDelay, bool bForceThrow)
			: this(null, null, null, iRetries, iDelay, bForceThrow)
		{
		}

		public RetryOnExceptionExecutionPolicy(IScheduler sRootScheduler, SchedulerDelegate sdSchedulerProcess, ExceptionHandlerDelegate ehdExceptionHandlerDelegate, int iRetries, int iDelay, bool bForceThrow)
			: base(sRootScheduler, sdSchedulerProcess, ehdExceptionHandlerDelegate)
		{
			this.iDelay			= iDelay;
			this.iRetries		= iRetries;
			this.bForceThrow	= bForceThrow;
		}

		public override void Execute(IScheduler sSourceScheduler)
		{
			for (int i = 0; i < iRetries; ++i)
			{
				try
				{
					sdSchedulerProcess(sSourceScheduler);
					break;
				}
				catch (Exception eException)
				{
					if (i >= (iRetries - 1))
					{
						if (ehdExceptionHandlerDelegate != null)
						{
							ehdExceptionHandlerDelegate(eException);
						}

						if (bForceThrow)
						{
							throw;
						}
					}
				}

				if (iDelay > 0)
				{
					Thread.Sleep(iDelay);
				}
			}
		}

		public override IExecutionPolicy Clone(SchedulerDelegate sdSchedulerProcess, ExceptionHandlerDelegate ehdExceptionHandlerDelegate)
		{
			RetryOnExceptionExecutionPolicy depNewPolicy = new RetryOnExceptionExecutionPolicy(sRootScheduler, sdSchedulerProcess, ehdExceptionHandlerDelegate, iRetries, iDelay, bForceThrow);

			return depNewPolicy;
		}
	}
}
